#include "my_param.h"
#include "perspective.h"

void ImagePerspective_Init(uint8 imageInput[IMAGE_HEIGHT][IMAGE_WIDTH], uint8 imageOutput[RESULT_HEIGHT][RESULT_WIDTH],
                           ImageDealDatatypedef image_deal[RESULT_HEIGHT])
{
    uint8 No_Angle = 0;                            // 无视角区域
    uint8 *PerImg_ip[RESULT_HEIGHT][RESULT_WIDTH]; // 逆透视之后的图像的指针
    
    for (int i = 0; i < RESULT_WIDTH; i++)
        for (int j = 0; j < RESULT_HEIGHT; j++)
        {
            int local_x = (int)((my_param.pers_Mat[0][0] * i + my_param.pers_Mat[0][1] * j + my_param.pers_Mat[0][2]) /
                                (my_param.pers_Mat[2][0] * i + my_param.pers_Mat[2][1] * j + my_param.pers_Mat[2][2]));
            int local_y = (int)((my_param.pers_Mat[1][0] * i + my_param.pers_Mat[1][1] * j + my_param.pers_Mat[1][2]) /
                                (my_param.pers_Mat[2][0] * i + my_param.pers_Mat[2][1] * j + my_param.pers_Mat[2][2]));
            if (local_x >= 0 && local_y >= 0 && local_x < IMAGE_WIDTH && local_y < IMAGE_HEIGHT)
                PerImg_ip[j][i] = &imageInput[local_y][local_x]; // 逆透视映射区域
            else
                PerImg_ip[j][i] = &No_Angle; // 逆透视因视角未能映射区域
        }

    // 确定有内容的边界
    for (int Y = RESULT_HEIGHT - 1; Y >= 0; Y--)
    {
        /*确定左边界*/
        image_deal[Y].Left_Sideline = 0; // 初始化边界赋值
        for (int X = 0; X < RESULT_WIDTH - 1; X++)
            if (PerImg_ip[Y][X] == &No_Angle && PerImg_ip[Y][X + 1] != &No_Angle)
            {
                image_deal[Y].Left_Sideline = X + 1;
                break;
            }

        /*确定右边界*/
        image_deal[Y].Right_Sideline = RESULT_WIDTH - 1; // 初始化边界赋值
        for (int X = 0; X < RESULT_WIDTH - 1; X++)
            if (PerImg_ip[Y][X] != &No_Angle && PerImg_ip[Y][X + 1] == &No_Angle)
            {
                image_deal[Y].Right_Sideline = X;
                break;
            }
    }

    for (int Ysite = 0; Ysite < RESULT_HEIGHT; Ysite++)
        for (int Xsite = 0; Xsite < RESULT_WIDTH; Xsite++)
            imageOutput[Ysite][Xsite] = *PerImg_ip[Ysite][Xsite];
}
